using System;
using System.Collections.Generic;
using System.Linq;
using VoiceAd.Models;
using System.Data.Linq.SqlClient;

namespace VoiceAd.DAL
{
    public class ProvinceRepository : IProvinceRepository, IDisposable
    {
        private dbVoiceAdDataContext context = new dbVoiceAdDataContext();

        public ProvinceRepository(dbVoiceAdDataContext db)
        {
            this.context = db;
        }

        public IEnumerable<tblProvince> GetListProvinces()
        {
            return context.tblProvinces.ToList();
        }

        public IEnumerable<tblProvince> GetListSearchProvinces(string ProvinceName)
        {
            IEnumerable<tblProvince> lst = from a in context.tblProvinces
                                           where SqlMethods.Like(a.ProvinceName, "%" + ProvinceName + "%")
                                           select a;

            return lst;
        }

        public IEnumerable<tblProvince> GetListProvinces(int id)
        {
            return context.tblProvinces.Where(x => x.AreaId == id).ToList();
        }

        public tblProvince GetProvinceById(int id)
        {
            return context.tblProvinces.Where(x => x.Id == id).FirstOrDefault();
        }

        public void InsProvince(tblProvince tblprovince)
        {
            context.tblProvinces.InsertOnSubmit(tblprovince);
            context.SubmitChanges();
        }

        public void UpdProvince(tblProvince tblprovince)
        {
            tblProvince obj = context.tblProvinces.Where(x => x.Id == tblprovince.Id).First();
            obj.ProvinceName = tblprovince.ProvinceName;
            context.SubmitChanges();
        }

        public void DelProvince(int id)
        {
            tblProvince obj = context.tblProvinces.Single(x => x.Id == id);
            context.tblProvinces.DeleteOnSubmit(obj);
            context.SubmitChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
